﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using System.Web.Security;
using Bzure.Security;
using Bzure.Security.Permissions;
using Bzure.Security.Principal;
using Bzure.Apps.Security.ViewModels;
using Bzure.Common.Core;
using Bzure.Apps.Security.ResourceFiles;


namespace Bzure.Apps.Security.Controllers
{
    [Export(typeof(IController)), ExportMetadata("Name", "Droit"), ExportMetadata("Area", "SecurityApp")]
    [Authorize]
    [SecurityAppAuthorize(RequiredRight = AdministrationRights.PermissionManage)]
    public class DroitController : T4ViewController
    {
        MasterViewModel MasterViewModel = new ViewModels.MasterViewModel()
        {
            Title = "通用权限管理"
        };
        [SecurityAppFilter(PageControllerItems.DroitConfigController)]
        public ActionResult Config(string id)
        {

            Type type = default(Type);
            foreach (KeyValuePair<Type, string> pair in Actor.Public.SystemRightTypes())
            {
                if (pair.Key.FullName == id)
                {
                    type = pair.Key;
                    break;
                }
            }

            DroitConfigViewModel ViewModel = new DroitConfigViewModel
            {
                DRList = Actor.Public.GetResourceByName(id),
                MasterViewModel = this.MasterViewModel,
                RList = Actor.Public.AsRoleManager().GetAllTeamRoles(),
                RS = EnumHelper.AllStringValue(type),
                ResourceName = EnumHelper.EnumName(type),
                Title = PermissionExtensions.RightGroupName(type) + "|" + EnumHelper.EnumName(type),
                Url = Url.RouteUrl("SecurityApp_Droit", new { action = "Config" })
            };
            return Result(ViewModel);
        }
        [HttpPost]
        [SecurityAppFilter(PageControllerItems.DroitConfigController)]
        public ActionResult Config(string id, FormCollection Collection)
        {
            Type type = default(Type);
            foreach (KeyValuePair<Type, string> pair in Actor.Public.SystemRightTypes())
            {
                if (pair.Key.FullName == id)
                {
                    type = pair.Key;
                    break;
                }
            }

            // 创建新的对应关系
            Dictionary<string, int> dc = new Dictionary<string, int>();
            foreach (string key in Collection.AllKeys.Where(m => m.StartsWith("RT_")))
            {
                string roleid = key.Split('_')[1];
                string v = Collection[key];
                int value = int.Parse(v);
                if (dc.ContainsKey(roleid))
                {
                    int val = dc[roleid];
                    dc[roleid] = val + value;
                }
                else
                {
                    dc[roleid] = value;
                }
            }
            List<DroitResource> drs = new List<DroitResource>();
            foreach (KeyValuePair<string, int> pair in dc)
            {
                drs.Add(new DroitResource(Guid.NewGuid().ToString())
                {
                    ResourceName = id,
                    RoleID = pair.Key,
                    RightValue = pair.Value,
                    State = 1
                });
            }

            NotificationViewModel notification = new NotificationViewModel();
            Actor.Public.ResetDroitResource(id, drs.ToArray(), (bool ok) =>
            {
                if (ok)
                {
                    notification.Data = NotificationData.YES;
                    notification.Content = string.Format("{0}授权保存成功", EnumHelper.EnumName(type));
                    notification.NotificationType = NotificationType.Success;
                }
                else
                {
                    notification.Data = NotificationData.NO;
                    notification.Content = string.Format("{0}授权保存失败", EnumHelper.EnumName(type));
                    notification.NotificationType = NotificationType.Error;
                }
            });

            return Result(notification);
        }
    }

}
